package george_foreman

class TournamentController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [tournamentInstanceList: Tournament.list(params), tournamentInstanceTotal: Tournament.count()]
    }

    def create = {
        def tournamentInstance = new Tournament()
        tournamentInstance.properties = params
        return [tournamentInstance: tournamentInstance]
    }

     def addPlayers = {
        long id = params.id as Long
        def tournament = Tournament.get(id)
        if (tournament == null) {
            throw new IllegalArgumentException("no tournament with id ${id}")
        }
        /*user.addToWall(user.currentStatus)
        Status newStatus = new Status(text: params.status)
        newStatus.save(failOnError: true)
        user.currentStatus = newStatus
        user.save(failOnError: true)
        redirect(action: 'show', id: id)*/
    }

    def save = {
        def tournamentInstance = new Tournament(params)
        params.each {key ->
            println(key)
        }
        if (tournamentInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'tournament.label', default: 'Tournament'), tournamentInstance.id])}"
            redirect(action: "show", id: tournamentInstance.id)
        }
        else {
            render(view: "create", model: [tournamentInstance: tournamentInstance])
        }
    }

    def show = {
        def tournamentInstance = Tournament.get(params.id)
        if (!tournamentInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'tournament.label', default: 'Tournament'), params.id])}"
            redirect(action: "list")
        }
        else {
            [tournamentInstance: tournamentInstance]
        }
    }

    def edit = {
        def tournamentInstance = Tournament.get(params.id)
        if (!tournamentInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'tournament.label', default: 'Tournament'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [tournamentInstance: tournamentInstance]
        }
    }

    def update = {
        def tournamentInstance = Tournament.get(params.id)
        if (tournamentInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (tournamentInstance.version > version) {
                    
                    tournamentInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'tournament.label', default: 'Tournament')] as Object[], "Another user has updated this Tournament while you were editing")
                    render(view: "edit", model: [tournamentInstance: tournamentInstance])
                    return
                }
            }
            tournamentInstance.properties = params
            def players = params.players.toList()
            new ArrayList(tournamentInstance.entrants).each{Entry entrant->
                println("Entrant is : " + entrant)
                println("Entrant is type : " + entrant.getClass())
                println("Player is : " + entrant.player)
                println("Player is type : " + entrant.player.getClass())
                println("Player ID is : " + entrant.player.id)
                println("Player ID is type : " + entrant.player.id.getClass())
                for (playa in params.players){
                    println("params.player is : " + playa)
                    println("params.player is type : " + playa.getClass())
                }
                if (!players.contains(entrant.player.id as String)){
                    def p = entrant.player
                    tournamentInstance.removeFromEntrants(entrant)
                    p.removeFromTournaments(entrant)
                    p.save(failOnError : true)
                    entrant.delete(failOnError : true)
                }
            }
            println("Step 1")
            players.each{playerID->
            println("Step 2 ${playerID}")
                for (Entry entrant : tournamentInstance.entrants) {
                    println("Step 3 ${entrant.player.id}")
                    if ((entrant.player.id as String).equals(playerID)){
                        println("step 4")
                        return
                    }
                }
                def player1= Player.get(playerID as Long)
                println("Player: " + player1)
                def entry = new Entry(player: player1, tournament: tournamentInstance)
                tournamentInstance.addToEntrants(entry)
                player1.addToTournaments(entry)
                player1.save(failOnError : true)
            }
            if (!tournamentInstance.hasErrors() && tournamentInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'tournament.label', default: 'Tournament'), tournamentInstance.id])}"
                redirect(action: "show", id: tournamentInstance.id)
            }
            else {
                render(view: "edit", model: [tournamentInstance: tournamentInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'tournament.label', default: 'Tournament'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def tournamentInstance = Tournament.get(params.id)
        if (tournamentInstance) {
            try {
                tournamentInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'tournament.label', default: 'Tournament'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'tournament.label', default: 'Tournament'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'tournament.label', default: 'Tournament'), params.id])}"
            redirect(action: "list")
        }
    }
}
